"""
STS协议基本使用示例
演示STS协议的基本功能
"""

import sys
import os
sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'src'))

from sts import STSProtocol, STSCrypto, STSToken, STSUtils
from meter import GasMeter
from vending import VendingSystem


def demo_basic_sts_protocol():
    """演示基本STS协议功能"""
    print("=== STS协议基本功能演示 ===")
    
    # 创建STS协议实例
    protocol = STSProtocol()
    
    # 获取协议信息
    protocol_info = protocol.get_protocol_info()
    print(f"协议名称: {protocol_info['protocol_name']}")
    print(f"协议版本: {protocol_info['version']}")
    print(f"加密方式: {protocol_info['encryption']}")
    print(f"CRC类型: {protocol_info['crc_type']}")
    print()
    
    # 开始会话
    meter_id = "123456789"
    session_result = protocol.start_session(meter_id)
    
    if session_result['success']:
        print(f"会话启动成功")
        print(f"表计ID: {session_result['meter_id']}")
        print(f"传输计数器: {session_result['transfer_counter']}")
        print(f"会话ID: {session_result['session_id']}")
        print()
        
        # 生成充值令牌
        amount = 5000  # 50元
        token_result = protocol.generate_recharge_token(amount)
        
        if token_result['success']:
            print(f"令牌生成成功")
            print(f"令牌: {token_result['token']}")
            print(f"金额: {token_result['amount_formatted']}")
            print(f"传输计数器: {token_result['transfer_counter']}")
            print()
            
            # 验证令牌
            verify_result = protocol.verify_recharge_token(token_result['token'])
            
            if verify_result['success']:
                print(f"令牌验证成功")
                print(f"验证金额: {verify_result['amount_formatted']}")
                print(f"验证表计ID: {verify_result['token_info']['meter_id']}")
            else:
                print(f"令牌验证失败: {verify_result['error']}")
        else:
            print(f"令牌生成失败: {token_result['error']}")
        
        # 结束会话
        end_result = protocol.end_session()
        print(f"会话结束: {end_result['success']}")
    else:
        print(f"会话启动失败: {session_result['error']}")
    
    print("\n" + "="*50 + "\n")


def demo_gas_meter_simulation():
    """演示燃气表模拟器功能"""
    print("=== 燃气表模拟器演示 ===")
    
    # 创建燃气表实例
    meter = GasMeter("123456789")
    
    # 开始通信
    comm_result = meter.start_communication()
    
    if comm_result['success']:
        print(f"通信启动成功")
        print(f"会话ID: {comm_result['session_id']}")
        print()
        
        # 读取表计数据
        data_result = meter.read_meter_data()
        
        if data_result['success']:
            print(f"表计数据读取成功")
            print(f"当前余额: {data_result['current_balance_formatted']}")
            print(f"总用气量: {data_result['total_consumption']} 立方米")
            print(f"表计状态: {data_result['status']}")
            print(f"报警状态: {data_result['alarm_status']}")
            print()
        
        # 模拟用气
        consumption_result = meter.simulate_consumption(2.0)  # 2小时用气
        
        if consumption_result['success']:
            print(f"用气模拟成功")
            print(f"用气时长: {consumption_result['duration_hours']} 小时")
            print(f"用气量: {consumption_result['volume']} 立方米")
            print(f"费用: {consumption_result['cost_formatted']}")
            print(f"新余额: {consumption_result['new_balance_formatted']}")
            print()
        
        # 结束通信
        end_result = meter.end_communication()
        print(f"通信结束: {end_result['success']}")
    else:
        print(f"通信启动失败: {comm_result['error']}")
    
    print("\n" + "="*50 + "\n")


def demo_vending_system():
    """演示售气系统功能"""
    print("=== 售气系统演示 ===")
    
    # 创建售气系统实例
    vending = VendingSystem()
    
    # 操作员登录
    login_result = vending.login_operator("OP001", "123456")
    
    if login_result['success']:
        print(f"操作员登录成功")
        print(f"操作员ID: {login_result['operator_id']}")
        print(f"会话ID: {login_result['session_id']}")
        print()
        
        # 生成充值令牌
        meter_id = "123456789"
        amount = 10000  # 100元
        
        token_result = vending.generate_token(meter_id, amount, "CASH")
        
        if token_result['success']:
            print(f"令牌生成成功")
            print(f"交易ID: {token_result['transaction_id']}")
            print(f"令牌: {token_result['token']}")
            print(f"金额: {token_result['amount_formatted']}")
            print(f"支付方式: {token_result['payment_method']}")
            print(f"操作员: {token_result['operator_id']}")
            print()
            
            # 获取交易信息
            txn_result = vending.get_transaction(token_result['transaction_id'])
            
            if txn_result['success']:
                print(f"交易信息获取成功")
                txn = txn_result['transaction']
                print(f"交易状态: {txn['status']}")
                print(f"创建时间: {txn['timestamp']}")
                print()
            
            # 获取系统统计
            stats_result = vending.get_transaction_statistics(24)
            
            if stats_result['success']:
                stats = stats_result['statistics']
                print(f"24小时交易统计")
                print(f"总交易数: {stats['total_transactions']}")
                print(f"成功交易数: {stats['completed_transactions']}")
                print(f"成功率: {stats['success_rate']:.1f}%")
                print(f"总金额: {stats['total_amount_formatted']}")
                print()
        
        # 操作员登出
        logout_result = vending.logout_operator()
        print(f"操作员登出: {logout_result['success']}")
    else:
        print(f"操作员登录失败: {login_result['error']}")
    
    print("\n" + "="*50 + "\n")


def demo_complete_workflow():
    """演示完整的充值工作流程"""
    print("=== 完整充值工作流程演示 ===")
    
    # 创建系统组件
    vending = VendingSystem()
    meter = GasMeter("123456789")
    
    # 1. 操作员登录
    print("1. 操作员登录")
    login_result = vending.login_operator("OP001", "123456")
    
    if not login_result['success']:
        print(f"登录失败: {login_result['error']}")
        return
    
    print(f"登录成功: {login_result['operator_id']}")
    print()
    
    # 2. 生成充值令牌
    print("2. 生成充值令牌")
    amount = 5000  # 50元
    token_result = vending.generate_token("123456789", amount, "CASH")
    
    if not token_result['success']:
        print(f"令牌生成失败: {token_result['error']}")
        return
    
    token = token_result['token']
    print(f"令牌生成成功: {token}")
    print(f"金额: {token_result['amount_formatted']}")
    print()
    
    # 3. 燃气表充值
    print("3. 燃气表充值")
    meter.start_communication()
    
    recharge_result = meter.recharge(token)
    
    if recharge_result['success']:
        print(f"充值成功")
        print(f"充值金额: {recharge_result['amount_formatted']}")
        print(f"充值前余额: {recharge_result['previous_balance']} 分")
        print(f"充值后余额: {recharge_result['new_balance_formatted']}")
        print()
        
        # 4. 验证充值结果
        print("4. 验证充值结果")
        meter_status = meter.get_meter_status()
        print(f"当前余额: {meter_status['current_balance_formatted']}")
        print(f"表计状态: {meter_status['status']}")
        print(f"报警状态: {meter_status['alarm_status']}")
        print()
        
        # 5. 模拟用气
        print("5. 模拟用气")
        consumption_result = meter.simulate_consumption(1.5)  # 1.5小时用气
        
        if consumption_result['success']:
            print(f"用气成功")
            print(f"用气量: {consumption_result['volume']} 立方米")
            print(f"费用: {consumption_result['cost_formatted']}")
            print(f"剩余余额: {consumption_result['new_balance_formatted']}")
        else:
            print(f"用气失败: {consumption_result['error']}")
    
    else:
        print(f"充值失败: {recharge_result['error']}")
    
    # 清理
    meter.end_communication()
    vending.logout_operator()
    
    print("\n" + "="*50 + "\n")


def main():
    """主函数"""
    print("STS预付费燃气表协议演示程序")
    print("="*50)
    
    # 演示各个功能模块
    demo_basic_sts_protocol()
    demo_gas_meter_simulation()
    demo_vending_system()
    demo_complete_workflow()
    
    print("演示完成！")


if __name__ == "__main__":
    main()
